import {
  getCardDetails,
  addReceivedCard,
  toMailList,
  connectCard
} from "../../apis/card";
import {
  clickNum
} from '../../apis/group';
import {
  globalData
} from '../../utils/request';
const app = getApp();

Page({
  data: {
    cardInfo: {},
    headHeight: null,
    headTop: null,
    touchStartY: 0,
    showTabs: false,
    showInfo: false,
    autoplay: false,
    current: 0,
    showReplay: false,
    showPlay: false,
    bgmPlay: false,
    musicPath: '',
    type: null,
    cardId: null,
    rCardId: null,
    bgm: null,
    isRequest: false
  },
  onLoad(options) {
    if (options.scene) {
      const scene = decodeURIComponent(options.scene);
      console.log(scene);
      options.cardId = scene.substr(3);
      options.type = 'qrCode';
    };
    let menu = wx.getMenuButtonBoundingClientRect();
    this.setData({
      headHeight: menu.height,
      headTop: menu.top + 2,
      ...options,
      ...globalData
    });

    if (options.from === 'group') this.upClickNum(options.groupId, options.cardId);

    if (options.type === 'addpreview') {
      this.data.cardInfo.imageList = wx.getStorageSync('img');
      this.setData({
        cardInfo: this.data.cardInfo,
        musicPath: options.musicPath
      });
    } else if (options.type === 'update') {
      this.getCardInfo(options.rCardId);
    } else {
      this.getCardInfo(options.cardId);
    };
  },

  // 右上角分享功能
  onShareAppMessage() {
    // let id = this.data.rCardId ? this.data.rCardId : this.data.cardId;
    return {
      title: this.data.cardInfo.userName + '的快名片',
      path: `/pages/cardPreview/index?from=${app.globalData.userName}&type=share&cardId=${this.data.cardInfo.cardId}`,
      imageUrl: `${this.data.cardInfo.avatar}`
    }
  },
  // 获取名片详情
  getCardInfo(id) {
    wx.showLoading({
      title: '加载中...',
      mask: true
    });
    getCardDetails(id).then(res => {
      if (res.data.code === 200) {
        let {
          data
        } = res.data;
        data.avatar = !new RegExp('https://').test(data.avatar) && !new RegExp('http://').test(data.avatar) ? app.globalData.url + data.avatar : data.avatar;
        if (!data.imageList) {
          wx.hideLoading({});
          this.setData({
            cardInfo: data
          });
        } else {
          data.imageList = data.imageList.map(v => {
            return v = !new RegExp('https://').test(v) && !new RegExp('http://').test(v) ? app.globalData.url + v : v;
          });
          wx.hideLoading({});
          this.setData({
            cardInfo: data
          });
        };

        if (data.cardType != 1) {
          wx.getStorage({
            key: 'historyPreview',
            success: res => {
              let arr = JSON.parse(res.data);
              if (arr.some(v => v.cardId == data.cardId || v.cardId == data.relCardId)) arr.splice(arr.findIndex(v => v.cardId == data.cardId || v.cardId == data.relCardId), 1);
              arr.unshift(data);
              wx.setStorage({
                data: JSON.stringify(arr),
                key: 'historyPreview'
              });
            },
            fail: res => {
              let arr = [data];
              wx.setStorage({
                data: JSON.stringify(arr),
                key: 'historyPreview'
              });
            }
          });
        };
      };
    });
  },
  // 收到的名片
  addHistory(id) {
    addReceivedCard(id).then(res => {
      if (res.data.code === 200) {
        this.data.cardInfo.cardId = res.data.data.cardId;
        this.setData({
          cardId: res.data.data.cardId,
          cardInfo: this.data.cardInfo
        });
      }
    });
  },

  upClickNum(groupId, cardId) {
    clickNum(groupId, cardId).then(res => {});
  },

  // 弹出信息
  ejectInfo() {
    this.setData({
      showInfo: !this.data.showInfo
    })
  },

  // 上滑下滑弹出
  touchStart(e) {
    let {
      pageY
    } = e.changedTouches["0"];
    this.setData({
      touchStartY: pageY
    });
  },
  touchEnd(e) {
    let {
      pageY
    } = e.changedTouches["0"];
    if (pageY - this.data.touchStartY < -100) {
      this.setData({
        showInfo: true
      });
    } else if (pageY - this.data.touchStartY > 100) {
      this.setData({
        showInfo: false
      });
    };
  },

  // 轮播图改变
  swiperChange(e) {
    let {
      current
    } = e.detail
    this.setData({
      current: current
    });
  },
  // 位置改变
  swiperPostionChange(e) {
    if (this.data.showReplay) {
      this.setData({
        showReplay: false
      });
    };
  },
  // 重新播放
  resetPlay() {
    if (this.data.showReplay) {
      this.setData({
        showReplay: false,
        autoplay: true,
        current: 0
      });
    };
  },

  goQRcode() {
    wx.navigateTo({
      url: `/pages/QRcode/index?type=user&cardId=${this.data.cardInfo.cardId}`,
    })
  },
  // 复制剪切板
  setClipboard() {
    // let info = this.data.cardInfo;
    // let str = `姓名：${info.userName}\n手机：${info.phone}\n公司：${info.company?info.company:'无信息'}\n职位：${info.post?info.post:'无信息'}\n邮箱：${info.mail?info.mail:'无信息'}`;
    wx.setClipboardData({
      data: this.data.cardInfo.phone,
      success: res => {
        wx.showToast({
          title: '已复制手机号',
          icon: 'success'
        });
      }
    });
  },
  // 前往编辑
  handleEdit() {
    wx.navigateTo({
      url: `/pages/editCard/index?type=edit&cardId=${this.data.cardInfo.cardId}`
    });
  },

  // 拨号
  callCard() {
    wx.makePhoneCall({
      phoneNumber: this.data.cardInfo.phone,
      success: res => {
        let data = {
          avatar: this.data.cardInfo.avatar,
          name: this.data.cardInfo.userName,
          phone: this.data.cardInfo.phone,
          firstPy: this.data.cardInfo.firstPy,
          date: new Date().getTime()
        };
        wx.getStorage({
          key: 'callLog',
          success: res => {
            let arr = JSON.parse(res.data);
            if (arr.some(v => v.phone == data.phone)) arr.splice(arr.findIndex(v => v.phone == data.phone), 1);
            arr.unshift(data);
            wx.setStorage({
              data: JSON.stringify(arr),
              key: 'callLog'
            });
          },
          fail: res => {
            let arr = [data];
            wx.setStorage({
              data: JSON.stringify(arr),
              key: 'callLog'
            });
          }
        });
      }
    });
  },

  bindgetuserinfo(e) {
    if (e.detail.userInfo) {
      app.globalData.userInfo = e.detail.userInfo;
      this.addCard();
    };
  },
  // 添加
  addCard() {
    if (this.data.cardInfo.ableAdd) {
      if (this.data.isRequest) return
      this.setData({
        isRequest: true
      });
      toMailList(this.data.cardId).then(res => {
        if (res.data.code === 200) {
          wx.showToast({
            title: '添加成功',
            icon: 'success',
            mask: true,
            duration: 1500
          });
          this.setData({
            isRequest: false,
            'cardInfo.ableAdd': false
          });
        };
      });
    } else {
      if (this.data.cardInfo.owner) {
        wx.showToast({
          title: '这是自己的名片...',
          icon: 'none'
        });
      } else {
        wx.showToast({
          title: '您已经保存过了...',
          icon: 'none'
        });
      };
    };
  },
  // 前往制作
  addMyCard() {
    wx.navigateTo({
      url: '/pages/makecard/index',
    });
  },

  // 关联
  updateCard() {
    connectCard(this.data.cardId, this.data.rCardId).then(res => {
      if (res.data.code === 200) {
        wx.showToast({
          title: '关联成功',
          icon: 'success',
          duration: 1500,
          success: res => {
            let timer = setTimeout(() => {
              wx.switchTab({
                url: '/pages/mailList/index',
              });
              clearTimeout(timer);
            }, 1500);
          }
        });
      };
    });
  },

  // 查看名片详细信息
  previewCardInfo() {
    wx.navigateTo({
      url: `/pages/cardDetails/index?from=swiper&cardId=${this.data.cardInfo.cardId}`
    });
  },

  // 返回
  goback() {
    if (this.data.musicPath) {
      this.data.bgm.stop();
    };

    if (this.data.type === 'addpreview') {
      wx.clearStorageSync('img');
      wx.navigateBack({
        delta: 1
      });
    } else if (this.data.type === 'share' || this.data.type === 'qrCode') {
      wx.switchTab({
        url: '/pages/mailList/index',
      });
    } else if (this.data.type === 'editPreview') {
      wx.switchTab({
        url: '/pages/personal/index',
      });
    } else {
      wx.navigateBack({
        delta: 1,
      });
    }
  },
  // 空函数
  emptyFunction() {},
})